package com.zxy.supplier_system.server.configuration

import com.fasterxml.jackson.databind.ObjectMapper
import org.hibernate.boot.model.FunctionContributions
import org.hibernate.boot.model.FunctionContributor
import org.hibernate.cfg.AvailableSettings
import org.hibernate.dialect.DatabaseVersion
import org.hibernate.dialect.MySQLDialect
import org.hibernate.dialect.function.StandardSQLFunction
import org.hibernate.type.format.jackson.JacksonJsonFormatMapper
import org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.data.auditing.DateTimeProvider
import org.springframework.data.jpa.repository.config.EnableJpaAuditing
import org.springframework.stereotype.Component
import java.time.OffsetDateTime
import java.util.*


@Configuration
@EnableJpaAuditing(dateTimeProviderRef = "dateTimeProvider")
class JpaConfiguration{
    @Bean
    fun jsonFormatMapperCustomizer(objectMapper: ObjectMapper): HibernatePropertiesCustomizer {
        return HibernatePropertiesCustomizer { properties: MutableMap<String, Any> ->
            properties[AvailableSettings.JSON_FORMAT_MAPPER] = JacksonJsonFormatMapper(objectMapper)
        }
    }

    @Bean
    fun dateTimeProvider() = DateTimeProvider { Optional.of(OffsetDateTime.now()) }
}

@Component
class IMysql8Dialect : MySQLDialect(DatabaseVersion.make(8))

class MyFunctionContributor : FunctionContributor{
    override fun contributeFunctions(functionContributions: FunctionContributions) {
        functionContributions.functionRegistry.register("greatest", StandardSQLFunction("greatest"))
    }

}